﻿package com.hykj.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hykj.dao.UserDao;
import com.hykj.valuebean.UserBean;

public class UserServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String servletPath = request.getServletPath();
		if ("/login".equals(servletPath)) {
			login(request, response);
		}
		
	}
	protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String message = "";
		String forward = "";
		
		String user = request.getParameter("user");
		String pswd = request.getParameter("pswd");
		String checkCode = request.getParameter("checkCode");
		try {
			UserBean loginer = new UserDao().getLoginer(user, pswd);
			if (checkCode != null) {
				String sRand = request.getSession().getAttribute("randCheckCode").toString().toUpperCase();
				if (checkCode.toUpperCase().equals(sRand)) {
					if (loginer != null) {
						request.getSession().setAttribute("loginer", loginer);
						forward = request.getContextPath() + "/admin/index";
						response.sendRedirect(forward);
					}
					else {
						message = "<li>用户名或密码错误</li><br>";
						message+= "<a href='javascript:window.history.go(-1)'>返回重试</a>";
						forward = "/admin/login.jsp";
						
						request.setAttribute("message", message);
						RequestDispatcher rd = request.getRequestDispatcher(forward);
						rd.forward(request, response);
					}
				} else {
					message = "<li>验证码错误错误</li><br>";
					message+= "<a href='javascript:window.history.go(-1)'>返回重试</a>";
					forward = "/admin/login.jps";
					
					request.setAttribute("message", message);
					RequestDispatcher rd = request.getRequestDispatcher(forward);
					rd.forward(request, response);
				}
				
			} else {
				message = "<li>请输入验证码</li><br>";
				message+= "<a href='javascript:window.history.go(-1)'>返回重试</a>";
				forward = "/admin/login.jsp";
				
				request.setAttribute("message", message);
				RequestDispatcher rd = request.getRequestDispatcher(forward);
				rd.forward(request, response);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
